<template>
    <div class="main-container">
        <TableBody>
            <template #header>
                <TableHeader :show-filter="false">
                    <template #search-content>
                        <a-form layout="inline" :model="searchData">
                            <a-form-item label="所属公司">
                                <a-select popup-container="html"  v-model="searchData.firm" @change="searchGsChange">
                                    <a-option v-for="(gc, index) in otherList.gcList" :key="index">{{ gc }}</a-option>
                                </a-select>
                            </a-form-item>
                            <a-form-item label="所属仓库">
                                <a-select popup-container="html"  v-model="searchData.warehouseName">
                                    <a-option v-for="(ck, index) in otherList.ckList" :key="ck.id">{{ ck.name }}
                                    </a-option>
                                </a-select>
                            </a-form-item>
                            <a-form-item label="布笼名称">
                                <a-input v-model="searchData.name"></a-input>
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" @click="doRefresh">查询</a-button>
                            </a-form-item>
                        </a-form>
                        <AddButton @click="onAddItem"></AddButton>
                    </template>
                </TableHeader>
            </template>
            <template #default>
                <a-table :bordered="false" :loading="tableLoading" :data="dataList" :pagination="pagination"
                    :row-key="rowKey">
                    <template #columns>
                        <a-table-column v-for="item of tableColumns" :key="item.key" :align="item.align"
                            :title="(item.title as string)" :width="item.width" :data-index="(item.key as string)"
                            :fixed="item.fixed">
                            <template v-if="item.key === 'index'" #cell="{ rowIndex }">
                                {{ rowIndex + 1 }}
                            </template>
                            <template v-else-if="item.key ==='isStop'" #cell="{ record }">
                                <a-switch :default-checked="record.isStop==1?true:false"
                                    @change="stateChange(record.id,$event)">
                                    <template #checked>
                                        开
                                    </template>
                                    <template #unchecked>
                                        关
                                    </template>
                                </a-switch>
                            </template>
                            <template v-else-if="item.key === 'actions'" #cell="{ record }">
                                <a-space>
                                    <a-button status="success" size="mini" @click="onUpdateItem(record)">编辑</a-button>
                                    <a-button status="success" size="mini" @click="openQrcode(record)">二维码</a-button>
                                    <a-button status="danger" size="mini" @click="onDeleteItem(record)">删除</a-button>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </template>
        </TableBody>

        <ModalDialog ref="modalDialogRef" :title="actionTitle" @confirm="editOk">
            <template #content>
                <a-form :model="editData">
                    <a-form-item label="所属工厂">
                        <a-select popup-container="html"  v-model="editData.firm">
                            <a-option v-for="(gc, index) in otherList.gcList" :key="index">{{ gc }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="所属仓库">
                        <a-select popup-container="html"  :default-value="editData.warehouseName" v-model="editData.warehouseName">
                            <a-option v-for="(item, index) in editCKlist" :key="index">{{ item.name }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="布笼编号" :rules="[{ required: true }]">
                        <a-input v-model="editData.code">
                        </a-input>
                    </a-form-item>
                    <a-form-item label="布笼名称">
                        <a-input v-model="editData.name"></a-input>
                    </a-form-item>
                </a-form>
            </template>
        </ModalDialog>
        <ModalDialog ref="qr2" :title="actionTitle" @confirm="editOk">
            <template #content>


                <a-alert type="error">当前二维码长期有效，请打印后妥善保存！</a-alert>

                <div style="margin:10px;text-align: center;">
                    <qrcode :size="150" :value="val"></qrcode>
                </div>
                <div>所属工厂：{{ qr.gc }}</div>
                <div>所属仓库：{{ qr.ck }}</div>
                <div>布笼名称：{{ qr.hj }}</div>


            </template>
        </ModalDialog>
    </div>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useRowKey, useTable, useTableColumn, usePagination } from '@/hooks/table'
import { ModalDialogType } from '@/types/components'
import { Message, Modal } from '@arco-design/web-vue'
import { defineComponent, toRaw, onMounted, ref, reactive, watch } from 'vue'
import qrcode from 'qrcode.vue'


export default defineComponent({
    name: 'Warehouse',
    components: { qrcode },
    setup() {
        // {“id”:"id","warehouse":"所属仓库","name":"布笼名称"}
        const table = useTable()
        const rowKey = useRowKey('id')
        const actionTitle = ref('添加仓库')

        const tableColumns = useTableColumn([
            table.indexColumn,
            {
                title: '所属工厂',
                key: 'firm',
                dataIndex: 'firm',
                width: 150,
            },
            {
                title: '所属仓库',
                key: 'warehouseName',
                dataIndex: 'warehouseName',
                width: 150,
            },
            {
                title: '所属布笼',
                key: 'shelveName',
                dataIndex: 'shelveName',
                width: 150,
            },
            {
                title: '储位编码',
                key: 'code',
                dataIndex: 'code',
                width: 150,
            },
            {
                title: '布笼名称',
                key: 'name',
                dataIndex: 'name',
                width: 150,
            },
            {
                title: '状态',
                key: 'isStop',
                dataIndex: 'isStop',
                width: 150,
            },
            {
                title: '操作',
                key: 'actions',
                dataIndex: 'actions',
                fixed: 'right',
                width: 150,
            },
        ])
        const pagination = usePagination(doRefresh)
        // 搜索对象
        interface huojiaModel {
            "id": number | string,
            "code": string,
            "firm": string,
            "warehouseName": string,
            "name": string,
            "isStop": string,
            "createName": string,
            "createDate": string
        }
        const searchData = reactive<huojiaModel>({
            "id": '',
            "code": "",
            "firm": "",
            "warehouseName": "",
            "name": "",
            "isStop": "",
            "createName": "",
            "createDate": "",
        })
        const otherList = reactive<any>({
            gcList: [],
            ckList: []
        })

        // 请求表格数据的方法
        function doRefresh() {
            post({
                url: 'storage/list',
                data: {
                    ...toRaw(searchData),
                    page: pagination.page,
                    size: pagination.pageSize
                },
            })
                .then(({ data, code }) => {
                    if (code === 200) {
                        table.handleSuccess(data.records);
                        pagination.setTotalSize(data.total)
                    }

                })
                .catch(console.log)
        }
        const editCKlist = ref<any[]>([])
        // 修改 使用的对象
        const editData = reactive<huojiaModel>({
            "id": '',
            "code": "",
            "firm": "",
            "warehouseName": "",
            "name": "",
            "isStop": "",
            "createName": "",
            "createDate": "",
        })
        watch(() => editData.firm, (n) => {
            post({
                url: 'warehouse/get',
                data: {

                    firm: editData.firm
                }
            }).then(({ data, code }) => {
                if (code === 200) {
                    editCKlist.value = data
                } else {
                    Message.warning('获取数据失败！')
                }
            })
                .catch(() => {
                    Message.warning('获取数据失败！')
                })

        })
        // 修改弹窗对象
        const modalDialogRef = ref<ModalDialogType | null>(null);

        function onAddItem() {
            editData.warehouseName = ''
            editData.code = ''
            editData.firm = ''
            editData.id = ''
            editData.name = ''
            editData.isStop = ''
            actionTitle.value = '添加布笼'
            modalDialogRef.value?.toggle()
        }

        function onUpdateItem(item: any) {

            editData.code = item.code
            editData.firm = item.firm
            editData.warehouseName = item.warehouseName
            editData.id = item.id
            editData.name = item.name
            actionTitle.value = '编辑布笼'
            post({
                url: 'warehouse/get',
                data: {

                    firm: editData.firm
                }
            }).then(({ data, code }) => {
                if (code === 200) {
                    editCKlist.value = data

                } else {
                    Message.warning('获取数据失败！')
                }
            })
                .catch(() => {
                    Message.warning('获取数据失败！')
                })

            modalDialogRef.value?.toggle()
        }
        function onDeleteItem(data: any) {
            Modal.confirm({
                title: '提示',
                content: '是否要删除此布笼？',
                cancelText: '取消',
                okText: '删除',
                onOk: () => {
                    post({
                        url: 'warehouse/delete',
                        data: [data.id]
                    }).then(({ code }) => {
                        if (code === 200) {
                            Message.success('删除成功')
                        } else {
                            Message.success('删除失败')
                        }
                    }).catch(() => {
                        Message.success('网络错误')
                    }).finally(() => {
                        doRefresh()
                    })
                },
            })
        }
        const gcList = ref<string[]>([])
        // 加载
        onMounted(() => {
            doRefresh()
            post({
                url: 'firm/getfrim',
                data:
                {
                    "firm": "",
                    "bumen": "",
                    "zu": "",
                    "ziwei": "",
                    "ren": ""
                }
            }).then((resp: any) => {
                otherList.gcList = resp.firmval.split(',')
            })


        })

        // 仓库状态修改事件
        const stateChange = (id: number, e: any) => {
            post({
                url: 'shelve/update',
                data: {
                    id: id,
                    isStop: e ? '1' : '0'
                }
            }).then(({ code }) => {
                if (code === 200) {
                    Message.success('修改成功')
                } else {
                    Message.success('修改失败')
                }
            })
        }
        const editOk = () => {
            if (actionTitle.value === "添加仓库") {
                post({
                    url: 'shelve/save',
                    data: {
                        ...toRaw(editData)
                    }
                }).then(({ data, code }) => {
                    if (code === 200) {
                        Message.success('添加成功')
                    } else {
                        Message.warning('添加失败')
                    }
                }).catch((err) => {
                    Message.error('网络错误')
                }).finally(() => {
                    modalDialogRef.value?.close()
                    doRefresh()
                })
            } else {
                post({
                    url: 'shelve/update',
                    data: {
                        ...toRaw(editData)
                    }
                }).then(({ data, code }) => {
                    if (code === 200) {
                        Message.success('修改成功')
                    } else {
                        Message.warning('修改失败')
                    }
                }).catch(() => {
                    Message.error('网络错误')
                }).finally(() => {
                    modalDialogRef.value?.close()
                    doRefresh()
                })
            }

        }
        const searchGsChange = () => {
            post({
                url: 'warehouse/get',
                data: {

                    firm: searchData.firm
                }
            }).then(({ data, code }) => {
                if (code === 200) {
                    otherList.ckList = data
                } else {
                    Message.warning('获取数据失败！')
                }
            })
                .catch(() => {
                    Message.warning('获取数据失败！')
                })
        }
        const qr2 = ref<ModalDialogType | null>(null);
        let val = ref('')
        const qr = reactive({
            gc: '',
            ck: '',
            hj: ''
        })
        const openQrcode = (item: any) => {
            qr.gc = item.firm
            qr.ck = item.warehouseName
            qr.hj = item.name
            val.value = JSON.stringify({ "id": item.id, "warehouse": item.warehouseName, "name": "" })
            qr2.value?.toggle()
        }

        return {
            qr,
            val,
            qr2,
            openQrcode,
            editCKlist,
            searchGsChange,
            otherList,
            editOk,
            gcList,
            pagination,
            modalDialogRef,
            stateChange,
            searchData,
            rowKey,
            editData,
            tableColumns,
            actionTitle,
            ...table,
            onAddItem,
            onDeleteItem,
            onUpdateItem,
            doRefresh
        }
    },
})
</script>
